package com.square.service.auth.consumer.aop;

import com.baomidou.mybatisplus.extension.api.R;
import com.square.service.auth.consumer.aop.annotation.RequiresPermissions;
import com.square.service.auth.consumer.feign.AuthFeign;
import com.square.service.common.consts.GlobalPrefix;
import com.square.service.common.handler.ApiCode;
import com.square.service.common.utils.AopUtil;
import com.square.service.common.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 权限认证注解切面通知
 *
 * @author : 王苏
 * @since : 2021/4/25 15:55
 */
@Slf4j
@Aspect
@Component
@Order(20)
public class RequiresPermissionsAspect {

    @Resource
    private AuthFeign authFeign;

    @Pointcut("@annotation(com.square.service.auth.consumer.aop.annotation.RequiresPermissions)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object arround(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = SpringContextUtil.getHttpServletRequest();
        String requestMethod = request.getMethod();
        String requestPath = request.getRequestURI().substring(request.getContextPath().length());
        requestPath = AopUtil.filterUrl(requestPath);
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        RequiresPermissions permissions = method.getAnnotation(RequiresPermissions.class);
        String[] value = permissions.value();
        log.debug("权限认证拦截请求 >> " + requestPath + ";请求类型 >> " + requestMethod + ";权限认证限制角色参数 >> " + Arrays.toString(value));
        String userKey = request.getHeader(GlobalPrefix.AUTHORIZATION_USERKEY);
        if (StringUtils.isBlank(userKey)) {
            return R.failed(ApiCode.INVALID_PROXY);
        }
        R<?> r = authFeign.doGetAuthorizationInfoForPermissions(userKey, value);
        if (!r.ok()) {
            return R.failed(r.getMsg());
        }
        return point.proceed();
    }


}
